
package com.wzt.lianfirecontrol;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;

import androidx.multidex.MultiDexApplication;

import com.mob.pushsdk.MobPush;
import com.mob.pushsdk.MobPushCustomMessage;
import com.mob.pushsdk.MobPushNotifyMessage;
import com.mob.pushsdk.MobPushReceiver;


import com.wzt.lianfirecontrol.activity.AlarmTranActivity;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.home.system.baojing.SysBaoJingDeviceDetailModel;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.http.HttpConnection;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.xh.common.thread.AsyncExecutor;

import org.json.JSONObject;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;

public class App extends MultiDexApplication {
    public static Context context;
    private static App mAppApplication;

    private static final int USER_CLICK_NITIFICATION = 100;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (USER_CLICK_NITIFICATION == msg.what){
                Bundle bundle = msg.getData();
                if (null != bundle){
                    String result = bundle.getString("result");
                    String value = bundle.getString("value");
                    if (!StringUtils.isEmpty(result)){
                        try {
                            JSONObject object = new JSONObject(result);
                            String data = object.optString("data");
                            if (!StringUtils.isEmpty(data)) {
                                SysBaoJingDeviceDetailModel sysDeviceDetailModel =
                                        JSONUtil.jsonObjectToBean(new JSONObject(data), SysBaoJingDeviceDetailModel.class);
                                // actionValue 0火警 1故障 2监管 3预警 （只有火警有警报画面）
                                String runStatus = "-1";
                                switch (value){
                                    case "0":
                                        runStatus = "1";
                                        break;
                                    case "1":
                                        runStatus = "2";
                                        break;
                                    case "2":
                                        runStatus = "4";
                                        break;
                                    case "3":
                                        runStatus = "98";
                                        break;
                                }
                                if (runStatus.equals(sysDeviceDetailModel.getRunStatus())){

                                    List<String> alias = UserInfoModel.getUserInfo(App.context).getRoleAlias();
                                    // 维保人员和维保管理人员只显示预约维保单
                                    // 消防安全责任人 消防安全管理人 不提示告警声音

                                    if (alias.contains(RoleConstant.ROLE_FIRE_SAFETY_LIABLE )||alias.contains(RoleConstant.ROLE_FIRE_SAFETY_CUSTODIAN )) {



                                    }else {

                                        Intent intent = new Intent(getApplicationContext(), AlarmTranActivity.class);
                                        intent.putExtra("pushBannerModle", bundle.getString("pushBannerModle"));
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);

                                    }

                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return false;
        }
    });


    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        mAppApplication = this;

        if (!ConstData.INNER) {
            AppExHandler crashHandler = AppExHandler.getInstance();
            crashHandler.init(this);//初始化全局异常捕获
        } else {
            // 允许chrome浏览器debug webview
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }
        // 内存泄漏检测初始化
    //    initCheck();
        initXutils();

        initAppAdaptation();
        // 初始化mob推送
        initNotifycation();
    }

//  private void initCheck() {
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            // This process is dedicated to LeakCanary for heap analysis.
//            // You should not init your app in this process.
//            return;
//        }
//        LeakCanary.install(this);
//    }

    private void initXutils() {
        x.Ext.init(this);
    }

    private void initNotifycation() {

        MobPush.initMobPush();
        //添加推送监听，可监听接收到的自定义消息（透传消息）、通知消息、通知栏点击事件、别名和标签变更操作。
        MobPush.addPushReceiver(new MobPushReceiver() {
            @Override
            public void onCustomMessageReceive(Context context, MobPushCustomMessage message) {
                //接收到自定义消息（透传消息）
                Log.e("xuhan", message.getContent());

                if (!StringUtils.isEmpty(message.getContent())) {
                    try {

                        BannerModel bannerModel = JSONUtil.jsonObjectToBean(new JSONObject(message.getContent()), BannerModel.class);

                        if (ConstData.ALARM.equals(bannerModel.getActionType())) {
                            AsyncExecutor.execute(new Runnable() {
                                @Override
                                public void run() {

                                    HashMap<String, Object> hashMap = new HashMap<>();
                                    hashMap.put("equId", bannerModel.getId());
                                    HashMap<String, String> params = new HashMap<>();
                                    params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
                                    String result = HttpConnection.postRequestByJsonWithOkHttp(App.getApp(), Url.DEVICE_DETAIL_URL, params);

                                    Message resultMessage = handler.obtainMessage();
                                    Bundle bundle = new Bundle();
                                    bundle.putString("result", result);
                                    bundle.putString("value", bannerModel.getActionValue());
                                    bundle.putString("pushBannerModle", message.getContent());
                                    resultMessage.setData(bundle);
                                    resultMessage.what = USER_CLICK_NITIFICATION;
                                    handler.sendMessage(resultMessage);
                                }
                            });

                        }else {
                            List<String> alias = UserInfoModel.getUserInfo(App.context).getRoleAlias();
                            // 维保人员和维保管理人员只显示预约维保单
                            // 消防安全责任人 消防安全管理人 不提示告警声音

                            if (alias.contains(RoleConstant.ROLE_FIRE_SAFETY_LIABLE )||alias.contains(RoleConstant.ROLE_FIRE_SAFETY_CUSTODIAN )) {



                            }else {

                                Intent intent = new Intent(getApplicationContext(), AlarmTranActivity.class);
                                intent.putExtra("pushBannerModle", message.getContent());
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);

                            }


                        }
                    }catch (Exception e){

                    }
                }
            }

            @Override
            public void onNotifyMessageReceive(Context context, MobPushNotifyMessage message) {
                //接收到通知消息
            }

            @Override
            public void onNotifyMessageOpenedReceive(Context context, MobPushNotifyMessage message) {
                //通知被点击事件
            }

            @Override
            public void onTagsCallback(Context context, String[] tags, int operation, int errorCode) {
                //标签操作回调
            }

            @Override
            public void onAliasCallback(Context context, String alias, int operation, int errorCode) {
                //别名操作回调

            }

        });

    }

    /** 获取Application */
    public static App getApp() {
        return mAppApplication;
    }

    private void initAppAdaptation() {
        if (Build.VERSION.SDK_INT >= 18) {
            // android 7.0系统解决拍照的问题
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
    }
}
